﻿Imports HslCommunication
Imports HslCommunication.LogNet
Imports HslCommunication.ModBus

Public Class Form1
    Private logfile As ILogNet
    Private busTcpClient As ModbusRtuOverTcp

    Private _ip As String
    Private _port As Integer
    Private WithEvents _timer As New Timer
    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub
    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        connectDB()
        busTcpClient = New ModbusRtuOverTcp(_ip, _port, 1)
        busTcpClient.AddressStartWithZero = True '首地址从0开始
        busTcpClient.IsStringReverse = True '字符串颠倒
        busTcpClient.DataFormat = HslCommunication.Core.DataFormat.DCBA
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        busTcpClient.SetPersistentConnection()
        Dim interval_Minute As Integer = 60 * 1000
        Try
            interval_Minute = CInt(getSysParam("equip_GL_interval_Minute")) * 60 * 1000
        Catch ex As Exception
            logfile.WriteError(ex.Message)
        End Try

        _timer.Interval = interval_Minute

        _timer_Tick(New Object, New EventArgs)
        _timer.Start()
    End Sub

    Public Sub connectDB()
        'イニシャルファイル情報取得
        g_szInitFileName = My.Application.Info.DirectoryPath & "\GuoLu.ini"

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)
        _ip = GetIniFile("GUOLU", "address", "172.16.19.235", g_szInitFileName)
        _port = GetIniFile("GUOLU", "port", "8899", g_szInitFileName)
        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Private Sub _timer_Tick(sender As Object, e As EventArgs) Handles _timer.Tick
        Dim readResult As OperateResult(Of Byte())
reload: readResult = busTcpClient.ReadFromCoreServer(HslCommunication.BasicFramework.SoftBasic.HexStringToBytes("02 03 00 01 00 0C 14 3C"))

        If readResult.IsSuccess = True Then
            lblDqsj.Text = Now
            lblLog.Text = HslCommunication.BasicFramework.SoftBasic.ByteToHexString(readResult.Content) & vbCrLf & lblLog.Text
            analyseResult(HslCommunication.BasicFramework.SoftBasic.ByteToHexString(readResult.Content))
        Else
            lblLog.Text = Now & readResult.ToMessageShowString & vbCrLf & lblLog.Text
            logfile.WriteError(readResult.ToMessageShowString)
            Threading.Thread.Sleep(1000)
            GoTo reload

        End If
    End Sub



    Private Sub analyseResult(str As String)
        Try

            'str = "0000000048CBE23842E59BD042BE288A41FD800042FE3800"
            Dim _index As Integer = str.Length / 2
            Dim _data(23) As Byte

            '分解数据
            For i As Integer = 0 To 23
                _data(i) = Convert.ToByte(str.Substring(i * 2, 2), 16)
            Next
            '前4位+后4位
            Dim _dataTotalB(3) As Byte
            Dim _dataTotalF(3) As Byte
            _dataTotalB(3) = _data(0)
            _dataTotalB(2) = _data(1)
            _dataTotalB(1) = _data(2)
            _dataTotalB(0) = _data(3)

            _dataTotalF(3) = _data(4)
            _dataTotalF(2) = _data(5)
            _dataTotalF(1) = _data(6)
            _dataTotalF(0) = _data(7)

            '总量
            lblTotal.Text = Math.Round(1000000 * BitConverter.ToSingle(_dataTotalB, 0) + BitConverter.ToSingle(_dataTotalF, 0), 4)

            '标况体积流量
            Dim _dataBiaoKuang(3) As Byte
            _dataBiaoKuang(3) = _data(8)
            _dataBiaoKuang(2) = _data(9)
            _dataBiaoKuang(1) = _data(10)
            _dataBiaoKuang(0) = _data(11)
            lblbiaokuang.Text = Math.Round(BitConverter.ToSingle(_dataBiaoKuang, 0), 2)

            Dim _dataGongKuang(3) As Byte
            _dataGongKuang(3) = _data(12)
            _dataGongKuang(2) = _data(13)
            _dataGongKuang(1) = _data(14)
            _dataGongKuang(0) = _data(15)
            lblgongkuang.Text = Math.Round(BitConverter.ToSingle(_dataGongKuang, 0), 2)

            Dim _dataWendu(3) As Byte
            _dataWendu(3) = _data(16)
            _dataWendu(2) = _data(17)
            _dataWendu(1) = _data(18)
            _dataWendu(0) = _data(19)
            lblwendu.Text = Math.Round(BitConverter.ToSingle(_dataWendu, 0), 2)

            Dim _dataYali(3) As Byte
            _dataYali(3) = _data(20)
            _dataYali(2) = _data(21)
            _dataYali(1) = _data(22)
            _dataYali(0) = _data(23)
            lblyali.Text = Math.Round(BitConverter.ToSingle(_dataYali, 0), 2)

            If insert(str, CSng(lblTotal.Text), CSng(lblbiaokuang.Text), CSng(lblgongkuang.Text), CSng(lblwendu.Text), CSng(lblyali.Text)) = -2 Then
                logfile.WriteError("数据保存错误")
            End If

        Catch ex As Exception
            logfile.WriteError(ex.Message)
        End Try
    End Sub

    Private Function insert(olddata As String, zongliang As Single, biaokuang As Single, gongkuang As Single, wendu As Single, yali As Single) As Integer
        Dim szSql As String = ""
        Dim rtn As Integer

        szSql &= " INSERT INTO sf.b_equip_info_guolu(savetime,olddata,zongliang,biaokuang,gongkuang,wendu,yali) VALUES (?,?,?,?,?,?,?)"

        rtn = DBacs.ExecuteUpdateSql(szSql, -1, Now, olddata, zongliang, biaokuang, gongkuang, wendu, yali)
        Return rtn
    End Function

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If MsgBox("如关闭系统，则停止监控 锅炉房的FCM型体积修正仪！" & vbCrLf & "确定要关闭吗？", 4, Me.Text) <> MsgBoxResult.Yes Then
            e.Cancel = True
        End If
    End Sub
End Class
